package ch.msoftch.gui.utils;

import org.eclipse.core.runtime.*;
import org.eclipse.jdt.core.dom.*;
import org.eclipse.jface.dialogs.*;
import org.eclipse.swt.widgets.*;

/**
 * Helper for eclipse stuff.
 * 
 * @author hautle
 */
public class EclipseHelper {
	/**
	 * Displays a error dialog.
	 * 
	 * @param shell The shell to use
	 * @param title The dialog title
	 * @param e The error
	 */
	public static void showError(Shell shell, String title, Exception e) {
		ErrorDialog.openError(shell, title, e.getMessage(), new Status(IStatus.ERROR, Activator.PLUGIN_ID, e.getMessage()));
	}

	/**
	 * Returns the full qualified name of the passed type.
	 * 
	 * @param type The type
	 * @return The full qualified name of the type
	 */
	public static String getFullQualifiedName(Type type) {
		return appendFullyQualifiedName(type, new StringBuilder()).toString();
	}

	/**
	 * Appends the fullqualified name of the passed type to the given buffer.
	 * 
	 * @param type The type
	 * @param buffer The buffer were to append the type name
	 * @return The passed buffer
	 */
	public static StringBuilder appendFullyQualifiedName(Type type, StringBuilder buffer) {
		switch (type.getNodeType()) {
			case ASTNode.ARRAY_TYPE:
				ArrayType arrayType = (ArrayType) type;
				appendFullyQualifiedName(arrayType.getElementType(), buffer);
				for (int i = 0, length = arrayType.getDimensions(); i < length; i++)
					buffer.append("[]");
				break;
			// case ASTNode.PARAMETERIZED_TYPE:
			// ParameterizedType parameterizedType = (ParameterizedType) type;
			// appendFullyQualifiedName(parameterizedType.getType(), buffer);
			// buffer.append('<');
			// boolean isFirst = true;
			// for (Type typeArgument : (Collection<Type>) parameterizedType.typeArguments()) {
			// if (!isFirst)
			// buffer.append(',');
			// else
			// isFirst = false;
			// appendFullyQualifiedName(typeArgument, buffer);
			// }
			// buffer.append('>');
			// break;
			case ASTNode.PRIMITIVE_TYPE:
				buffer.append(((PrimitiveType) type).getPrimitiveTypeCode().toString());
				break;
			case ASTNode.QUALIFIED_TYPE:
				buffer.append(((QualifiedType) type).getName().getFullyQualifiedName());
				break;
			case ASTNode.SIMPLE_TYPE:
				buffer.append(((SimpleType) type).getName().getFullyQualifiedName());
				break;
			case ASTNode.WILDCARD_TYPE:
				buffer.append('?');
				WildcardType wildcardType = (WildcardType) type;
				Type bound = wildcardType.getBound();
				if (bound == null)
					return buffer;
				if (wildcardType.isUpperBound())
					buffer.append(" extends ");
				else
					buffer.append(" super ");
				appendFullyQualifiedName(bound, buffer);
				break;
		}
		return buffer;
	}
}
